package com.chenwang.measure.model;

import android.content.Context;
import android.text.TextUtils;


import com.chenwang.measure.model.bean.DataBean;
import com.chenwang.measure.model.bean.UploadBean;
import com.chenwang.measure.model.bean.WorkBean;
import com.chenwang.measure.model.bean.WorkTaskBean;
import com.chenwang.measure.ui.adapter.AdapterIntegerDefault0;
import com.chenwang.measure.ui.adapter.DoubleDefault0Adapter;
import com.chenwang.measure.utils.FileUtils;
import com.chenwang.measure.utils.MyLogger;
import com.chenwang.measure.utils.MyToast;
import com.chenwang.measure.utils.RxUtils;
import com.chenwang.measure.utils.SharePreferenceUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;


import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import okhttp3.Response;

/**
 * @松 on 2019/6/25 14:22
 * 重新封装
 */
public class OkgoNetwork {
    private I mI;

    public OkgoNetwork(I i) {
        mI = i;
    }

    public interface I{

        void download(List<WorkBean.OverviewDOListBean> list);
        void uploadSuccess(boolean bool,List<File> files);
    }



    /**
     * 下载任务
     * @param context 上下文
     * @param list    本地所有任务
     * @param name    姓名
     * @param ip      ip
     */
    public void  download(Context context, final List<WorkBean.OverviewDOListBean> list , final String name , final String ip){

          Observable.create(new ObservableOnSubscribe<Boolean>() {
               @Override
               public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {


                   HashMap<String,Object> map = new HashMap<>();
                   map.put("name", name);
                   JSONObject jsonObject = new JSONObject(map);
                   Response response =OkGo.<String>post("http://"+ip+"/app/open/exportOverview")
                           .upJson(jsonObject.toString())
                           .execute();
                   String json = response.body().string();
                   Gson gson = new GsonBuilder()
                           .registerTypeAdapter(Integer.class, new AdapterIntegerDefault0())
                           .registerTypeAdapter(int.class, new AdapterIntegerDefault0())
                           .registerTypeAdapter(Double.class, new DoubleDefault0Adapter())
                           .registerTypeAdapter(double.class, new DoubleDefault0Adapter())
                           .create();
                   MyLogger.i(json);
                   WorkBean workBean = gson.fromJson(json,WorkBean.class );
                   if (workBean.getCode() ==0){
                       for (WorkBean.OverviewDOListBean w:workBean.getOverviewDOList()){
                           w.setMissionState(0);
                           list.add(0,w );
                       }
                       FileUtils.writeFile(Constant.path+Constant.fileName, gson.toJson(list), false);
                       emitter.onNext(true);
                   }else {
                       MyToast.show(workBean.getMsg());
                       emitter.onNext(false);

                   }



               }
           }).compose(RxUtils.<Boolean>io_main()).subscribe(new ObserverOnNext<Boolean>() {
               @Override
               public void onNext(Boolean bool) {
                        if (true) {
                            mI.download(list);
                        }else {
                            mI.download(null);
                        }
               }

           });


    }

    /**
     * 上传
     * @param list  要上传的任务
     * @param ip    ip
     * @param lists 本地所有任务
     */
    public void upload(final  List<WorkBean.OverviewDOListBean> list , final String ip , final List<WorkBean.OverviewDOListBean> lists){
//
        final List<File> files = new ArrayList<>();
        Observable.create(new ObservableOnSubscribe<Boolean>() {
            @Override
            public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {


                List<UploadBean> uploadBeans = new ArrayList<>();

                for (WorkBean.OverviewDOListBean bean:list){
                    List<UploadBean.detailedDOVMS> detailedDOVMS = new ArrayList<>();
                     UploadBean uploadBean = new UploadBean();
                     for (WorkBean.OverviewDOListBean.DetailedDOsBean d :bean.getDetailedDOs()){
                          UploadBean.detailedDOVMS dovms = new UploadBean.detailedDOVMS();
                          if (!TextUtils.isEmpty(d.getImageUrl())){
                              int i = d.getImageUrl().lastIndexOf("/");
                              int point = d.getImageUrl().lastIndexOf(".");

                                   /*  System.out.println("上传图片名字："+d.getImageUrl().substring(i+1,point));
                                     files.add(new File(d.getImageUrl().substring(0, i+1),
                                             d.getImageUrl().substring(i+1,d.getImageUrl().length())));*/

                                    dovms.setImageUrl(d.getImageUrl().substring(i+1,point));
                             // dovms.setImageUrl(FileUtils.imageToBase64(d.getImageUrl()));
                          }
                          if (!TextUtils.isEmpty(d.getLineType())) {
                              dovms.setLineType(Integer.valueOf(d.getLineType()));
                          }
                          dovms.setLonAndlat(d.getLonAndlat());
                          if (!TextUtils.isEmpty(d.getMultipoint())) {
                              dovms.setMultipoint(d.getMultipoint());
                          }
                          dovms.setRwmxId(d.getRwmxId());
                          dovms.setSemaphoreSpace(d.getSemaphoreSpace());
                          detailedDOVMS.add(dovms);
                     }
                     uploadBean.setRwgsId(bean.getRwgsId());
                     uploadBean.setDetailedDOs(detailedDOVMS);
                     uploadBeans.add(uploadBean);

                }
                Gson gson = new Gson();
                String json = gson.toJson(uploadBeans);
                System.out.println(json);
                Response response =OkGo.<String>post("http://"+ip+"/app/open/uploadingOverview")
                        .upJson(json)
                        .execute();
                String s = response.body().string();
                MyLogger.i(s);
                DataBean dataBean = gson.fromJson(s, DataBean.class);
                if (dataBean.getCode() == 0){
                    MyToast.show(dataBean.getMsg());
                    emitter.onNext(FileUtils.writeFile(Constant.path+Constant.fileName, gson.toJson(lists), false));
                }else {
                    MyToast.show(dataBean.getMsg());
                    emitter.onNext(false);
                }




            }
        }).compose(RxUtils.<Boolean>io_main()).subscribe(new ObserverOnNext<Boolean>() {
            @Override
            public void onNext(Boolean bool) {
                     mI.uploadSuccess(bool , files);
            }

        });



    }


}
